/*
 * thread_pool.cpp
 *
 *  Created on: 2008-12-15
 *      Author: fanliangliang
 */

#include "thread_pool.h"
#include "foreach.h"
#include "bind.h"

BEGIN_NAMESPACE_TOXIC

ThreadPool::ThreadPool(size_t size) {
	_threads.reserve(size);
	for (size_t i = 0; i < size; ++i) {
		Thread* thread = new Thread(toxic::bind(&ThreadPool::work, this));
		thread->start();
		_threads.push_back(thread);
	}
}

ThreadPool::~ThreadPool() {
	wait();
}

void ThreadPool::wait() {
	if (_queue.interrupt()) {
		foreach (Thread* t, _threads) {
			t->join();
			delete t;
		}
		_threads.clear();
	}
}

void ThreadPool::work() {
	Runnable* task = 0;
	while (_queue.pop(task)) {
		if (task != 0) {
			task->run();
			delete task;
		}
	}
}

END_NAMESPACE_TOXIC
